package factorytest.iflytek.com.einkiflytekfactorytest.engineerui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.common.PermissionManager;
import factorytest.iflytek.com.einkiflytekfactorytest.iflytekWakeup.HtfyunWakeupEngine;
import factorytest.iflytek.com.einkiflytekfactorytest.iflytekWakeup.HtfyunWakeuperListener;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;

/**
 * Created by sst on 2018/7/10.
 */

public class WakeupActivity extends Activity {

    public static final int WAKE_UP_TIME_SECOND = 30;
    public static final int SUCCESS_WAKEUP_COUNT = 7;

    private Button btnFail;

    private TextView txtStatus;
    private TextView txtCount;
    private TextView txtTips;
    private TextView txtCountDown;

    private HtfyunWakeupEngine wakeupEngine;

    private Handler mHandler;
    private Context mContext;

    private int wakeupCount = 0;
    private boolean canWakeup = false;
    private int wakeupCountDown = WAKE_UP_TIME_SECOND;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_wakeup);

        findViewById(R.id.btnFail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishWithFail();
            }
        });


        txtStatus = (TextView) findViewById(R.id.txtStatus);
        txtCount = (TextView) findViewById(R.id.txtCount);
        txtTips = (TextView) findViewById(R.id.txtTips);
        txtCountDown = (TextView) findViewById(R.id.txtCountDown);


        txtTips.setText(getString(R.string.test_wakeup_tips, WAKE_UP_TIME_SECOND));
        txtCount.setText(getString(R.string.wakeup_success_count, wakeupCount, (SUCCESS_WAKEUP_COUNT - wakeupCount)));
        txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.wakeup_status_start_recognition)));

        mContext = this;
        mHandler = new MyHandler(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        initPermission();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if(mHandler.hasMessages(MSG_START)){
            mHandler.removeMessages(MSG_START);
        }

        if (mHandler.hasMessages(MSG_COUNT_DOWN)) {
            mHandler.removeMessages(MSG_COUNT_DOWN);
        }

        destroyIflytekVoiceRecognition();

    }


    private void initPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE

                    );

        } else {

            startRecognition();

        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        DebugLog.e("wakeup ~~~~~~~~~~~~~~onRequestPermissionsResult");

        startRecognition();


    }


    private void startRecognition() {
        if(!mHandler.hasMessages(MSG_START)){
            Message msg = mHandler.obtainMessage(MSG_START);
            mHandler.sendMessageDelayed(msg,DELAY_START);
        }
    }

    private void initIflytekVoiceRecognition() {

        destroyIflytekVoiceRecognition();

        wakeupEngine = new HtfyunWakeupEngine(mContext);
        wakeupEngine.setHtfyunWakeuperListener(new WakeupListener());
        wakeupEngine.start();

        canWakeup = true;

        txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.wakeup_status_doing)));
    }

    private void destroyIflytekVoiceRecognition() {

        if (wakeupEngine != null) {
            wakeupEngine.destroy();
            wakeupEngine = null;
        }

    }

    private void handleRecognition() {

        txtCount.setText(getString(R.string.wakeup_success_count, wakeupCount, (SUCCESS_WAKEUP_COUNT - wakeupCount)));

        if (wakeupCount >= SUCCESS_WAKEUP_COUNT) {
            canWakeup = false;
            txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.test_result_pass)));

            finishWithOK();

        } else if (!canWakeup) {
            txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.test_result_fail)));
        }
    }

    private void finishWithOK() {
        Toast.makeText(mContext, R.string.test_ok, Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(this);
    }

    private void finishWithFail() {
        Toast.makeText(mContext, R.string.test_fail, Toast.LENGTH_SHORT).show();
        setResult(RESULT_CANCELED);
        ActivityCompat.finishAfterTransition(this);
    }

    private void updateCountdown() {

        if (wakeupCountDown <= 0) {
            finishWithFail();
        }

        txtCountDown.setText(getString(R.string.wakeup_test_countdown, wakeupCountDown));
        wakeupCountDown--;

        mHandler.sendEmptyMessageDelayed(MSG_COUNT_DOWN, PERIOD_COUNT_DOWN);
    }


    private static final int MSG_START = 100;
    private static final int DELAY_START = 1000;

    private static final int MSG_COUNT_DOWN = 1000;
    private static final int PERIOD_COUNT_DOWN = 1000;

    private final static class MyHandler extends Handler {

        private WeakReference<WakeupActivity> reference;

        public MyHandler(WakeupActivity activity) {
            reference = new WeakReference<WakeupActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            WakeupActivity activity = reference.get();
            if (activity == null) {
                return;
            }

            if (msg.what == MSG_START) {
                activity.initIflytekVoiceRecognition();

            }
        }
    }

    private class WakeupListener implements HtfyunWakeuperListener {
        @Override
        public void onWakeUp(String json) {

            if (!canWakeup) {
                return;
            }

            wakeupCount++;

            handleRecognition();
        }

        @Override
        public void onError(String error) {
            Toast.makeText(mContext, error, Toast.LENGTH_LONG).show();
        }
    }

}
